<template>
  <div class="login-container">
    <!-- 顶部背景 -->
    <div class="login-header">
      <div class="welcome-text">数字化企业管理</div>
      <div class="welcome-text">和团队协作</div>
      <div class="welcome-text">一个OA就够了</div>
    </div>

    <!-- 登录表单 -->
    <div class="login-form">
      <!-- 手机号登录表单 -->
      <template v-if="loginType === 'phone'">
        <!-- 手机号输入框 -->
        <div class="phone-input">
          <van-field
            v-model="formData.phone"
            placeholder="请输入手机号"
            class="input-field"
            autocomplete="off"
          >
            <template #label>
              <div class="area-code" @click="goToCountrySelect">
                {{ selectedCountry.code }}
                <van-icon name="arrow-down" />
              </div>
            </template>
          </van-field>
        </div>

        <!-- 验证码输入框 -->
        <van-field
          v-model="formData.code"
          center
          placeholder="请输入验证码"
          label=""
          class="input-field"
          autocomplete="off"
        >
          <template #button>
            <van-button
              size="small"
              class="send-code-btn"
              :disabled="countdown > 0"
              @click="sendCode"
            >
              {{ codeButtonText }}
            </van-button>
          </template>
        </van-field>
      </template>

      <!-- 账号密码登录表单 -->
      <template v-else>
        <!-- 账号输入框 -->
        <van-field
          v-model="formData.account"
          placeholder="请输入账号"
          class="input-field"
          :rules="[{ required: true, message: '请输入账号' }]"
          autocomplete="off"
        />

        <!-- 密码输入框 -->
        <van-field
          v-model="formData.password"
          :type="showPassword ? 'text' : 'password'"
          placeholder="请输入密码"
          class="input-field"
          :rules="[{ required: true, message: '请输入密码' }]"
          autocomplete="off"
        >
          <!-- 忘记密码链接和查看密码图标 -->
          <template #button>
            <div style="display: flex; align-items: center;">
              <van-icon
                :name="showPassword ? 'eye-o' : 'closed-eye'"
                style="margin-right: 8px;"
                @click="showPassword = !showPassword"
              />
              <van-button
                size="small"
                class="send-code-btn"
                @click="goToResetPassword"
              >
                忘记密码？
              </van-button>
            </div>
          </template>
        </van-field>
      </template>

      <!-- 登录按钮 -->
      <div class="login-btn-wrapper">
        <van-button
          block
          class="login-btn"
          :loading="loading"
          @click="handleLogin"
        >
          登录
        </van-button>
      </div>

      <!-- 底部链接区域 -->
      <div class="bottom-links">
        <div class="register-link" @click="goToRegister">注册账号</div>
        <div class="switch-login-type" @click="switchLoginType">
          {{ loginType === "phone" ? "账号登录" : "手机号登录" }}
        </div>
      </div>
    </div>

    <!-- loading组件 -->
    <div v-if="loading" class="loading-wrapper">
      <van-loading type="spinner" size="40px" text="加载中..." vertical>
        加载中...</van-loading
      >
    </div>
  </div>
</template>


<script lang="ts" setup>
import { ref, reactive, onMounted, onUnmounted } from "vue";
import { showToast } from "vant";
import { useRouter } from "vue-router";
import countriesData from "@/data/countries.json";
import { loginApi, sendSmsCode } from "@/api/index";
import { storage } from "@/utils/storage";

// 定义国家类型
interface Country {
  name: string;
  code: string;
  countryCode: string;
  flag: string;
}

// 路由实例
const router = useRouter();

// 表单数据
const formData = reactive({
  phone: "",
  code: "",
  account: "", // 修改字段名为account
  password: "",
});

// 状态变量
const loading = ref(false);
const countdown = ref(0);
const codeButtonText = ref("获取验证码");
const loginType = ref("password"); // 默认为账号密码登录
const showPassword = ref(false); // 控制密码可见性
let timer: number | null = null;

// 国家选择相关
const countries = ref(countriesData);
const selectedCountry = ref(countries.value[0]); // 默认选择中国

// 切换登录方式
const switchLoginType = () => {
  loginType.value = loginType.value === "phone" ? "password" : "phone";
  // 切换时清空表单
  formData.phone = "";
  formData.code = "";
  formData.account = "";
  formData.password = "";
};

// 返回上一页
const goBack = () => {
  router.back();
};

// 跳转到国家选择页面
const goToCountrySelect = () => {
  sessionStorage.setItem(
    "selectedCountryCode",
    selectedCountry.value.countryCode
  );
  router.push({
    path: "/country-select",
    query: { from: "login" },
  });
};

// 跳转到注册页面
const goToRegister = () => {
  router.push("/register");
};

// 跳转到重置密码页面
const goToResetPassword = () => {
  router.push("/reset-password");
};

// 监听路由返回，获取选择的国家
onMounted(() => {
  const selectedCountryCode = router.currentRoute.value.query
    .selectedCountry as string;
  if (selectedCountryCode) {
    const country = countries.value.find(
      (c) => c.countryCode === selectedCountryCode
    );
    if (country) {
      selectedCountry.value = country;
    }
  }
});

// 发送验证码
const sendCode = async () => {
  if (countdown.value > 0) return;

  if (!formData.phone) {
    showToast("请输入手机号");
    return;
  }

  if (
    selectedCountry.value.countryCode === "CN" &&
    !/^1[3-9]\d{9}$/.test(formData.phone)
  ) {
    showToast("请输入正确的手机号");
    return;
  }

  try {
    const response = await sendSmsCode({ phone: formData.phone });

    if (response.code === 0) {
      countdown.value = 60;
      codeButtonText.value = `${countdown.value}s`;

      timer = window.setInterval(() => {
        countdown.value--;
        codeButtonText.value = `${countdown.value}s`;

        if (countdown.value <= 0) {
          clearInterval(timer as number);
          codeButtonText.value = "获取验证码";
          countdown.value = 0;
        }
      }, 1000);

      showToast({ type: "success", message: response.msg || "验证码已发送" });
    } else {
      showToast(response.msg || "发送验证码失败");
    }
  } catch (error) {
    console.error("发送验证码失败:", error);
    showToast("发送验证码失败，请稍后重试");
  }
};

// 处理登录
const handleLogin = async () => {
  if (loginType.value === "phone") {
    // 手机号登录验证
    if (!formData.phone || !/^1[3-9]\d{9}$/.test(formData.phone)) {
      showToast("请输入正确的手机号");
      return;
    }

    if (!formData.code) {
      showToast("请输入验证码");
      return;
    }

    try {
      loading.value = true;
      const response = await loginApi({
        phone: formData.phone,
        smsCode: formData.code,
        loginType: 1, // 添加登录类型参数: 1-手机号
      });

      if (response.code === 0) {
        // 先保存用户信息，这样后续保存 token 时会使用正确的 userId
        storage.setUserInfo(response.data);
        
        // 再保存 token
        if (response.data.accessToken) {
          storage.setItem("accessToken", response.data.accessToken);
        }
        if (response.data.refreshToken) {
          storage.setItem("refreshToken", response.data.refreshToken);
        }
        
        showToast({ type: "success", message: "登录成功" });
        // 直接跳转到首页
        router.replace("/home");
      } else {
        showToast(response.msg || "登录失败");
      }
    } catch (error) {
      console.error("登录失败:", error);
      showToast("登录失败，请稍后重试");
    } finally {
      loading.value = false;
    }
  } else {
    // 账号密码登录验证
    if (!formData.account) {
      showToast("请输入账号");
      return;
    }

    if (!formData.password) {
      showToast("请输入密码");
      return;
    }

    try {
      loading.value = true;
      const response = await loginApi({
        account: formData.account,
        password: formData.password,
        loginType: 2, // 添加登录类型参数: 2-密码
      });

      if (response.code === 0) {
        // 先保存用户信息，这样后续保存 token 时会使用正确的 userId
        storage.setUserInfo(response.data);
        
        // 再保存 token
        if (response.data.accessToken) {
          storage.setItem("accessToken", response.data.accessToken);
        }
        if (response.data.refreshToken) {
          storage.setItem("refreshToken", response.data.refreshToken);
        }
        
        showToast({ type: "success", message: "登录成功" });
        // 直接跳转到首页
        router.replace("/home");
      } else {
        showToast(response.msg || "登录失败");
      }
    } catch (error) {
      console.error("登录失败:", error);
      showToast("登录失败，请稍后重试");
    } finally {
      loading.value = false;
    }
  }
};

// 组件销毁时清除定时器
onUnmounted(() => {
  if (timer) {
    clearInterval(timer);
  }
});
</script>
<style lang="scss" scoped>
@import url("./style/index.scss");
</style>